// pages/mall/submitOrder/index.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import { clearShopCartStorage, deEmptyChildrenCascader } from '../../../../utils/hooks';
import * as Storage from '../../../../utils/storage';
import subPub from '../../../../utils/subPub';
import {
  formatDateString,
  getFormatDays,
  getMinuteIntTime,
  getOptimizeDateTwo,
  initLocationPersmiss,
  judgeAuth
} from '../../../../utils/util';

const $api = require('../../../../request/api').API;
const app = getApp();
const fifteenTimes = getMinuteIntTime(15);
/**
 * addressType有八种类型
 * 1：呼叫器本身地址下单
 * 2：呼叫器地址和联系人下单，这里需要填写联系电话和联系人
 * 3：符合就近收货地址下单，这个是会定位获取最近的收货地址下单
 * 4：呼叫器地址和门牌号下单，这里需要填写电话号码、联系人、门牌号
 * 5：用户新地址下单，需要用户去新增地址下单
 * 6：呼叫器地址和层、门牌号下单，需要用户去选择层、填写门牌号
 * 7：呼叫器地址和单元、层、门牌号下单，需要用户去选择单元、层、填写门牌号
 * 8：呼叫器地址和栋、单元、层、门牌号下单，需要用户去选择栋、单元、层、填写门牌号
 *
 */
Page({
  data: {
    beeperId: '',
    btnId: '',
    btnServerClassifyIds: '',
    queryType: '',
    addressType: 1,
    latitude: '',
    longitude: '',
    harvestAddressId: '',
    address: '', //地址位置
    linkName: '',
    phone: '',
    houseNumber: '',
    provinceName: '',
    provinceId: '',
    cityName: '',
    cityId: '',
    areaName: '',
    areaId: '',
    streetName: '',
    streetId: '',
    villageId: '',
    villageName: '',
    shopCartList: [],
    shopCartListTwo: [], //根据商家分好类的订单

    shopList: [], //提交的商品数据
    variantIds: '', //商品所有的id
    totalPrice: '',
    remainder: '', //余额
    isExpand: false, //是否展开
    initNum: 4, //不需要展开时的个数
    payType: '2',
    remark: '',
    recordRemark: '',
    deliveryAmount: '',
    realDeliveryAmount: '',
    packageAmount: '',
    depositAmount: '',
    showAddressPicker: false, //地址列表弹框的显示
    addressList: [],
    formList: [], //生成的表单
    tempFormList: [], //缓存的formList
    // formType:0,//附加信息类别
    goodsFormList: [], // 每个产品的表单信息
    loadData: true, //因为每次选图片都会触发onShow,所以用一个变量来控制
    beeperType: '', // 1是公共呼叫器，2是专属呼叫器
    mainFlag: '', //0 表示用户不是主用户 其它值表示用户是主用户
    monthPay: false, //为true表示可以月结
    offlineBalancePay: false, //表示可以线下月结
    businessesBalance: null, //会员余额
    payWxAppUrl: '',
    showPayQrcode: false,
    beeperExistAddress: 1, //1表示呼叫器存在地址，0表示呼叫器不存在地址
    off: 0, //公共呼叫器非主用户是否存在联系电话联系地址
    existAddress: 1, //如果地址类型是五，且没有填写过地址
    status: 0, //0表示没有符合条件的地址
    inputPerson: '',
    inputPhone: '',
    inputHouseNumber: '',
    inputHouseNumberId: '',
    beeperLongitude: '',
    beeperLatitude: '',
    // 是否只能微信支付
    onlyWx: false,
    // 是否允许提交
    permSubmit: false,

    // 推广员收益
    promoteGain: 0,
    payableAmount: 0,
    showPromoter: false,
    showTime: false,
    visitFlag: false,

    orderSource: '', // orderSource：3表示资讯页来的下单，5表示活动下单
    sourceId: '', // 活动id

    timeActiveIndex: 0,
    timeActiveId: null,
    timeList: [],
    serveDates: getFormatDays(7),
    serveTimes: [],
    showServeTimeRange: false,
    showServeTime: {
      show: false,
      minMinute: 0,
      maxMinute: 60,
      minHour: '',
      maxHour: '',
      time: '',
      empty: false
    },
    residentAddress: {
      value: '',
      show: false,
      buildId: '',
      buildName: '',
      floorId: '',
      floorName: '',
      unitId: '',
      unitName: '',
      title: '栋单元层',
      name: '', // 组合名称
      fieldNames: { text: 'name', value: 'id' },
      options: []
    },
    deductionFee: ['1', '2']
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let beeperId = app.globalData['btnList.beeperId'];
    let latitude = app.globalData['btnList.latitude'];
    let longitude = app.globalData['btnList.longitude'];
    let btnId = app.globalData['btnList.btnId'];
    let btnServerClassifyIds = app.globalData['btnList.btnServerClassifyIds'];
    let queryType = app.globalData['btnList.queryType'];
    let shopCartList = [];
    let tempFormList = [];
    if (app.globalData.goodsList) {
      // 直接下单来的
      shopCartList = app.globalData.goodsList;
      tempFormList = app.globalData.tempFormList || [];
      delete app.globalData.goodsList;
      delete app.globalData.tempFormList;
    } else if (options.combineId) {
      // 如果存在combineId就表示是组合产品下单
      let res = await this.getGoodsListByCombinId(options.combineId, options.nums);
      shopCartList = res.list;
      shopCartList[0].ruleId = res.ruleId;
    } else {
      shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
      tempFormList = JSON.parse(wx.getStorageSync('formList') || '[]');
    }

    if (options.another) {
      // 如果是再来一单来的，必须清空购物车,必须清除全局关键字
      wx.setStorageSync('shopCartData', JSON.stringify([]));
      wx.setStorageSync('formList', JSON.stringify([]));
    }
    this.setData({
      beeperId: beeperId ? beeperId : '',
      btnId: btnId,
      btnServerClassifyIds: btnServerClassifyIds,
      queryType: queryType,
      latitude: latitude ? parseFloat(latitude) : '',
      longitude: longitude ? parseFloat(longitude) : '',
      shopCartList,
      tempFormList,
      variantIds: shopCartList.map(item => item.variantId).join(','),
      visitFlag: shopCartList.some(item => item.visitFlag),
      orderSource: options.orderSource,
      sourceId: options.sourceId,
      btnName: options.btnName,
      eventId: app.globalData['btnList.eventId']
    });
    await this.getFormInfo();
    this.judgeWxPay();
    this.classifyByBusinessName();
    await this.getPortionInfo();
    if (!latitude && this.data.addressType == 3) {
      try {
        let res = await judgeAuth('scope.userLocation');
        if (!res) {
          await Dialog.confirm({
            title: '提示',
            message: '是否通过定位来获取附近收货地址？'
          });
          if (res === false) {
            res = await openAuth('scope.userLocation');
          }
        }
        if (res !== false) {
          // 是undefined或者为true的时候才定位
          res = await initLocationPersmiss();
          this.setData({
            latitude: res.location.lat,
            longitude: res.location.lng
          });
        }
      } finally {
        await this.getAddress();
        //
      }
    } else {
      await this.getAddress();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    if (!this.alreadyCome) {
      // 第一次进来不需要执行onShow
      this.alreadyCome = true;
      return;
    }

    if (app.globalData.saveRemark) {
      this.setData({
        remark: app.globalData.remark ? app.globalData.remark : '',
        recordRemark: app.globalData.recordRemark ? app.globalData.recordRemark : ''
      });
      app.globalData.saveRemark = null;
    }

    if (!app.globalData.exceed && !app.globalData.delete && !app.globalData.harvestAddressId && !this.data.loadData) {
      // 选择图片视频会触发onShow，这里就是比避免这个操作
      return;
    }
    if (app.globalData.exceed || app.globalData.delete) {
      // 如果修改的地址是现在选中的地址超出了范围就需要把选中地址清空
      if (app.globalData.harvestAddressId == this.data.harvestAddressId) {
        this.setData({
          harvestAddressId: '',
          linkName: '',
          phone: '',
          address: '',
          houseNumber: '',
          villageName: ''
        });
      }
      this.showAddressPopup();
    } else if (app.globalData.harvestAddressId) {
      // 地址是符合的地址
      this.setData({
        harvestAddressId: app.globalData.harvestAddressId,
        linkName: app.globalData.linkName,
        phone: app.globalData.phone,
        address: app.globalData.address,
        houseNumber: app.globalData.houseNumber,
        showAddressPicker: false,
        villageName: app.globalData.villageName,
        existAddress: 1,
        beeperExistAddress: 1,
        status: 1
      });
    }

    // 每次进来都需要获取价格
    this.countPrice();
    delete app.globalData.harvestAddressId;
    delete app.globalData.address;
    delete app.globalData.villageName;
    delete app.globalData.linkName;
    delete app.globalData.phone;
    delete app.globalData.houseNumber;
    delete app.globalData.exceed;
    delete app.globalData.delete;

    this.setData({
      loadData: false
    });
  },
  // 阻止冒泡
  stopBubble() {},
  // 姓名输入
  inputPersonChange(e) {
    this.setData({
      inputPerson: e.detail.value
    });
  },
  // 电话输入
  inputPhoneChange(e) {
    this.setData({
      inputPhone: e.detail.value
    });
  },
  // 门牌号数据输入
  inputHouseNumberChange(e) {
    this.setData({
      inputHouseNumber: e.detail.value
    });
  },
  showResidentAddressPopup(e) {
    this.setData({
      'residentAddress.show': true
    });
  },
  closeResidentAddress() {
    this.setData({
      'residentAddress.show': false
    });
  },
  confirmResidentAddress(e) {
    const { selectedOptions } = e.detail;
    let { residentAddress, addressType, inputHouseNumber, inputHouseNumberId } = this.data;
    let { buildId, buildName, unitId, unitName, floorId, floorName, houseNumber, houseNumberId } = residentAddress;
    let name = '';
    switch (addressType) {
      case 6:
        floorId = selectedOptions[0].id;
        floorName = selectedOptions[0].name;
        inputHouseNumber = selectedOptions[1].name
        inputHouseNumberId = selectedOptions[1].id
        name = floorName;
        break;
      case 7:
        unitId = selectedOptions[0].id;
        unitName = selectedOptions[0].name;
        name = unitName;
        if (selectedOptions[1]) {
          floorId = selectedOptions[1].id;
          floorName = selectedOptions[1].name;
          name = name + '/' + floorName;
        }
        if (selectedOptions[2]) {
          inputHouseNumber = selectedOptions[2].name
          inputHouseNumberId = selectedOptions[2].id
        }
        break;
      case 8:
        buildId = selectedOptions[0].id;
        buildName = selectedOptions[0].name;
        name = buildName;
        if (selectedOptions[1]) {
          unitId = selectedOptions[1].id;
          unitName = selectedOptions[1].name;
          name = name + '/' + unitName;
          if (selectedOptions[2]) {
            floorId = selectedOptions && selectedOptions[2].id;
            floorName = selectedOptions && selectedOptions[2].name;
            name = name + '/' + floorName;
          }
          if (selectedOptions[3]) {
            inputHouseNumber = selectedOptions[3].name
            inputHouseNumberId = selectedOptions[3].id
          }
        }
        break;
    }
    // console.log(buildId,buildName,unitId,unitName,floorId,floorName,e.detail.value,name)
    Object.assign(residentAddress, {
      buildId,
      buildName,
      unitId,
      unitName,
      floorId,
      floorName,
      value: e.detail.value,
      name
    });
    this.setData({ residentAddress, inputHouseNumber, inputHouseNumberId });
    this.closeResidentAddress();
  },
  // 去呼叫器地址设置页面
  toBeeperAddress() {
    wx.navigateTo({
      url:
        '/subcontract/person/pages/beeperAddress/index?id=' + this.data.beeperId + '&variantIds=' + this.data.variantIds
    });
  },
  // 判段否只能微信支付
  judgeWxPay() {
    if (this.data.shopCartList.some(item => item.goodsType == 3)) {
      this.setData({
        onlyWx: true
      });
    }
  },
  // 把购物车根据商户名称分类
  classifyByBusinessName() {
    let list = Array.from(new Set(this.data.shopCartList.map(item => item.businessId)));
    this.data.shopCartListTwo = [];
    list.forEach((item, index) => {
      this.data.shopCartListTwo[index] = {
        businessName: '',
        businessId: '',
        list: []
      };
      this.data.shopCartList.forEach(item2 => {
        if (item2.activeDiscount) {
          item2.activePrice = item2.active.activePrice;
        }
        if (item == item2.businessId) {
          if (!this.data.shopCartListTwo[index].businessId) {
            this.data.shopCartListTwo[index].businessName = item2.businessName;
            this.data.shopCartListTwo[index].businessId = item2.businessId;
          }
          this.data.shopCartListTwo[index].list.push({ ...item2 });
        }
      });
    });
    this.moreGoods();
  },
  // 过多的产品需要点击更多才可以看到
  moreGoods() {
    let nums = 0;
    // 哪些需要初始展示的商品添加属性initShow
    this.data.shopCartListTwo.forEach(item => {
      item.list.forEach(item2 => {
        if (++nums < this.data.initNum) {
          item2.initShow = true;
        }
      });
    });
    // 需要展示的商铺名称也添加initShow
    this.data.shopCartListTwo.forEach(item => {
      if (item.list.some(item => item.initShow)) {
        item.initShow = true;
      }
    });
    this.setData({
      shopCartListTwo: this.data.shopCartListTwo,
      initNum: nums
    });
  },
  // 显示收货地址弹框
  showAddressPopup() {
    Toast.loading({ message: '加载中...', forbidClick: true, duration: 0 });
    let params = {
      beeperId: this.data.beeperId,
      variantIds: this.data.variantIds
    };
    $api
      .addressList(params)
      .then(res => {
        let data = res.data.data;
        let exceed = false; //这个用来标识第一个超出配送地址的一项
        data.forEach(item => {
          if (!exceed && !item.state) {
            item.exceed = true;
            exceed = true;
          }
          item.villageName = item.villageName || '';
          item.address = item.address || '';
        });
        this.setData({
          addressList: data,
          showAddressPicker: true
        });
        Toast.clear();
      })
      .catch(() => {
        Toast.clear();
      });
  },
  // 选择地址
  selectAddress(e) {
    let item = e.currentTarget.dataset.item;
    if (!item.state) {
      Toast.fail('该地址不在商家配送范围');
      return;
    }
    this.setData({
      harvestAddressId: item.harvestAddressId,
      address: item.address,
      linkName: item.linkName,
      phone: item.phone,
      houseNumber: item.houseNumber,
      villageName: item.villageName,
      showAddressPicker: false
    });
    this.countPrice();
  },
  // 关闭收货地址弹框
  closeAddressPopup() {
    this.setData({
      showAddressPicker: false
    });
  },
  // 去编辑或添加地址
  toSelectAddress(e) {
    let item = e.currentTarget.dataset.item;
    if (!item) {
      // item不存在就表示是添加收货地址，variantIds表示是从订单页面去的地址选择页面
      const { beeperId, addressType, existAddress } = this.data;
      // relationBeeperId: this.data.beeperId,
      // relationBeeperType:this.data.addressType
      let str = !existAddress ? '&relationBeeperId=' + beeperId + '&relationBeeperType=' + addressType : '';
      wx.navigateTo({
        url: '/subcontract/person/pages/selectAddress/index?variantIds=' + this.data.variantIds + str
      });
      return;
    }
    let beeperId = item.beeperId;
    let harvestAddressId = item.harvestAddressId;
    if (beeperId) {
      // 如果呼叫器存在就去呼叫器地址选择页面，beeeprAddressId表示是从订单页面取得，回来的时候需要获取选中呼叫器地址
      wx.navigateTo({
        url: '/subcontract/person/pages/beeperAddress/index?id=' + beeperId + '&variantIds=' + this.data.variantIds
      });
    } else if (harvestAddressId) {
      // beeperId不存在但是harvestAddressId存在就去收货地址选择页面
      wx.navigateTo({
        url:
          '/subcontract/person/pages/selectAddress/index?id=' + harvestAddressId + '&variantIds=' + this.data.variantIds
      });
    }
  },
  // 获取地址
  async getAddress() {
    let params = {
      beeperId: this.data.beeperId,
      variantIds: this.data.variantIds,
      latitude: this.data.latitude,
      longitude: this.data.longitude
    };

    try {
      let data = await $api.getAddress(params);
      this.tempAddress = data = data.data.data;

      let beeperId = this.data.beeperId;
      if (beeperId && !data) {
        // 呼叫器自己都没有地址，那就需要先完善呼叫器地址
        this.setData({
          beeperExistAddress: 0
        });
        return;
      } else if (data.status) {
        // status存在表示当前地址不符合条件，需要自己去选择
        this.setData({
          status: 1,
          existAddress: this.data.addressType == 5 ? 0 : 1
        });
        this.showAddressPopup();
        return;
      }

      // else{
      //   this.setData({
      //     showAddressPicker:false
      //   })
      // }
      const modifyData = {
        showAddressPicker: false,
        harvestAddressId: data.harvestAddressId,
        address: data.address,
        beeperLatitude: data.latitude,
        beeperLongitude: data.longitude,
        linkName: data.linkName || '',
        phone: data.phone || '',
        houseNumber: data.houseNumber,
        provinceName: data.provinceName,
        provinceId: data.provinceId,
        cityName: data.cityName,
        cityId: data.cityId,
        areaName: data.areaName,
        areaId: data.areaId,
        streetName: data.streetName,
        streetId: data.streetId,
        villageName: data.villageName,
        villageId: data.villageId,
        off: data.off
      };

      if (data.off == 2) {
        // off存在表示addressType为2、4、6、7、8中的一种，且还需要完善内容
        modifyData.inputPerson = wx.getStorageSync('nickName');
        modifyData.inputPhone = wx.getStorageSync('phone');
        modifyData.storagePhone = modifyData.inputPhone; // 这里做一个标识，标识本已经绑定手机号

        switch (this.data.addressType) {
          case 6:
            this.getResidentAddressList({ parentId: this.data.residentAddress.unitId });
            modifyData['residentAddress.title'] = '层';
            break;
          case 7:
            this.getResidentAddressList({ parentId: this.data.residentAddress.buildId });
            modifyData['residentAddress.title'] = '单元层';
            break;
          case 8:
            this.getResidentAddressList({ villageId: data.villageId });
            modifyData['residentAddress.title'] = '栋单元层';
            break;
        }
      }
      this.setData(modifyData);
      // 获取到地址后就计算价格
      this.countPrice();
    } catch (err) {
      Toast.clear();
    }
  },
  // 获取住户栋单元层地址
  async getResidentAddressList(params) {
    let res = await $api.getResidentAddressList(params);
    res = res.data.data || [];
    deEmptyChildrenCascader(res);
    this.setData({
      'residentAddress.options': res
    });
  },
  async getPhoneNumber(e) {
    let cond = {
      code: e.detail.code,
      appId: Storage.APPID
    };
    let res = await $api.getPhone(cond);
    res = res.data.data;
    if (!res) return;
    this.setData({
      inputPhone: res
    });
  },
  // 保存地址
  async saveAddress() {
    const {
      addressType,
      houseNumber,
      inputHouseNumber,
      inputHouseNumberId,
      linkPhone,
      linkName,
      inputPhone,
      inputPerson,
      beeperLatitude,
      beeperLongitude,
      address,
      provinceName,
      provinceId,
      cityName,
      cityId,
      areaName,
      areaId,
      streetName,
      streetId,
      villageId,
      villageName,
      beeperId,
      residentAddress
    } = this.data;
    const { floorId, unitId, buildId, floorName, unitName, buildName } = residentAddress;

    const params = Object.assign(
      { ...this.tempAddress },
      {
        latitude: beeperLatitude,
        longitude: beeperLongitude,
        phone: linkPhone,
        linkName,
        address,
        provinceName,
        provinceId,
        cityName,
        cityId,
        areaName,
        areaId,
        streetName,
        streetId,
        villageId: villageId || '',
        houseNumber,
        houseNumberId: inputHouseNumberId,
        villageName: villageName || '',
        relationBeeperId: beeperId,
        relationBeeperType: addressType
      }
    );
    if (addressType == 2 || addressType == 4 || addressType == 6 || addressType == 7 || addressType == 8) {
      params.phone = inputPhone;
      params.linkName = inputPerson;
      if (addressType !== 2) {
        params.houseNumber = inputHouseNumber;
        params.houseNumberId = inputHouseNumberId
      }
      if (addressType == 6 || addressType == 7 || addressType == 8) {
        // 678类型需要传栋单元层
        params.floorId = floorId;
        params.unitId = unitId;
        params.buildId = buildId;
        params.floorName = floorName;
        params.unitName = unitName;
        params.buildName = buildName;
      }
    }
    const res = await $api.saveAddress(params);

    this.setData({
      off: 0,
      linkName,
      phone: linkPhone,
      houseNumber
    });
    return res.data.data;
  },
  // 获取表单信息
  async getFormInfo() {
    const { shopCartList } = this.data;
    const params = shopCartList.reduce((a, b) => {
      if (a.ruleIds) {
        return {
          ruleIds: a.ruleIds + ',' + b.ruleId,
          thirdClassifyIds: a.thirdClassifyIds + ',' + b.thirdClassifyId,
          serverIds: a.serverIds + ',' + b.serverId,
          goodsIds: a.goodsIds + ',' + b.goodsId,
          businessIds: a.businessIds + ',' + b.businessId
        };
      } else {
        return {
          ruleIds: String(b.ruleId),
          thirdClassifyIds: String(b.thirdClassifyId),
          serverIds: String(b.serverId),
          goodsIds: String(b.goodsId),
          businessIds: String(b.businessId)
        };
      }
    }, {});
    const res = await $api.getFormInfo(params);
    let data = res.data.data || [];
    let arr = data['1'] || [];
    let goodsFormList = [];
    for (let key in arr) {
      arr[key].forEach(item => {
        if (!item.goodsId) {
          item.goodsId = shopCartList.find(item2 => item2.serverId == item.serverId).goodsId;
        }
        if (!item.serverId) {
          item.serverId = shopCartList.find(item2 => item2.goodsId == item.goodsId).serverId;
        }
      });
      // 以下是对比本地存储的属性属性attrId一样就获取本地存储的值
      const id = arr[key][0].goodsId + '-' + arr[key][0].serverId;
      const obj = {
        id,
        name: arr[key][0].serverName || arr[key][0].goodsName,
        list: arr[key],
        introduce: arr[key][0].introduce
      };
      this.data.tempFormList.forEach(item => {
        if (item.id == id) {
          obj.list.forEach((item2, index) => {
            const val = item.list.find(item3 => item3.attrId == item2.attrId);
            if (val) {
              obj.list[index] = val;
            }
          });
        }
      });
      goodsFormList.push(obj);
    }
    const formList = data['2'] || [];
    this.setData({
      formList,
      goodsFormList
    });
    formList
      .flatMap(item => item)
      .concat(goodsFormList.flatMap(item => item.list))
      .find(item => {
        if (item.fieldName == 'consumer') {
          this.getMainList();
          return true;
        }
      });
  },
  // 获取主用户列表
  async getMainList() {
    const res = await $api.getBeeperCustomer({ beeperId: this.data.beeperId });
    const data = (res.data.data || []).map(item => item.name);
    if (data.length) {
      app.globalData['custom-form-selectedList'] = data;
      subPub.emit('getBeeperCustomerList', data);
    }
  },
  // 获取商品信息
  async getGoodsListByCombinId(combineId, nums) {
    let params = {
      combineId: combineId,
      nums: nums
    };
    let res = await $api.getGoodsListByCombinId(params);
    const { data } = res.data;
    data.list.forEach(item => {
      item.mainImage = item.images;
    });
    return data;
  },
  // 选择支付方式
  clickPayStyle(e) {
    let payType = e.currentTarget.dataset.type;
    if (payType == 1 && this.data.totalPrice > this.data.remainder) {
      wx.navigateTo({
        url: '/subcontract/equipment/pages/topUp/index?id=' + this.data.beeperId
      });
      return;
    } else {
      this.setData({
        payType
      });
    }
  },
  // 点击展开或者收起
  clickExpandStow(e) {
    this.setData({
      isExpand: e.currentTarget.dataset.flag
    });
  },
  // 获取配送费和包装费,并计算总价
  async countPrice() {
    if (!this.data.harvestAddressId) {
      // 判断是否存在地址，不存在清除价格
      this.setData({
        packageAmount: '',
        deliveryAmount: '',
        totalPrice: ''
      });
      return;
    }
    let params = {
      list: this.data.shopCartList.map(item => ({
        beeperBtnId: item.id,
        nums: item.nums,
        variantId: item.variantId,
        goodsType: item.goodsType,
        variantIds: item.relationVariantIds ? item.relationVariantIds : '',
        name: item.name
      })),
      addressId: this.data.harvestAddressId,
      beeperId: this.data.beeperId
    };
    let data = await $api.getCaculatePrice(params);
    data = data.data.data;
    let packageAmount = data.list.reduce((a, b) => a + b.packageAmount, 0);
    let deliveryAmount = data.list.reduce((a, b) => a + b.deliveryAmount, 0);
    let totalPrice = data.list.reduce((a, b) => a + b.payAmount, 0);
    let payableAmount = data.list.reduce((a, b) => a + b.payableAmount, 0);
    let depositAmount = data.list.reduce((a, b) => a + b.depositAmount, 0);
    let promoteGain = data.list.reduce((a, b) => a + b.promoteGain, 0);

    this.data.shopCartListTwo = data.list;
    this.data.initNum = 4;
    this.data.shopCartListTwo.forEach(item => {
      item.list.forEach(item2 => {
        item2.mainImage = item2.images;
        item2.relationGoodsNames = (item2.oGRelations || [])
          .map(item3 => item3.name + (item3.sku ? '/' + item3.sku : ''))
          .join('、');
        item2.serveDate = '';
        item2.serveTime = '';
      });

      if (item.expectedTimeStr) {
        // optimizeDate 是展示的日期，而selectedTime是统一格式的字符串日期yyyy-MM-dd MM:hh:ss
        item.optimizeDate = getOptimizeDateTwo(item.expectedTimeStr);
      }
    });
    this.moreGoods();
    this.setData({
      shopList: data,
      packageAmount: parseFloat(packageAmount.toFixed(2)),
      deliveryAmount: parseFloat(deliveryAmount.toFixed(2)),
      realDeliveryAmount: parseFloat((deliveryAmount + 0.5).toFixed(2)),
      totalPrice: parseFloat((totalPrice - data.discountOld - data.discountPmc).toFixed(2)),
      depositAmount: parseFloat(depositAmount.toFixed(2)),
      payableAmount: parseFloat((payableAmount - data.discountOld - data.discountPmc).toFixed(2)),
      promoteGain: parseFloat(promoteGain.toFixed(2))
    });
    if (this.data.monthPay || this.data.offlineBalancePay) {
      // 如果可以线下月季或者线下余额支付
      let flag = false;
      if (this.data.monthPay) {
        // flag为true表示所有商户的会员余额都足够，那么就选线下余额支付，不可以选月结
        flag = data.list.some(item => {
          const businessesBalance = this.data.businessesBalance;
          return Object.keys(businessesBalance).some(
            key => key == item.businessId && item.payAmount > businessesBalance[key]
          );
        });
      }
      this.setData({
        monthPay: flag,
        offlineBalancePay: !flag,
        payType: flag ? '6' : '7'
      });
    } else {
      this.setData({
        payType:
          this.data.beeperId && this.data.mainFlag && this.data.totalPrice < this.data.balance && !this.data.onlyWx
            ? '1'
            : '2'
      });
    }
    wx.nextTick(() => {
      this.setData({
        permSubmit: true
      });
    });
  },
  /**
   * 获取呼叫器结算的一些信息
   */
  async getPortionInfo() {
    const { beeperId, shopCartList } = this.data;
    const params = {
      beeperId,
      businessIds: shopCartList.map(item => item.businessId).toString()
    };
    const res = await $api.getPortionInfo(params);
    let data = res.data.data;
    const modifyData = {
      remainder: data.balance,
      beeperType: data.beeperType,
      addressType: data.addressType,
      payWxAppUrl: data.payWxAppUrl,
      mainFlag: data.mainFlag,
      monthPay: data.monthPay,
      offlineBalancePay: data.offlineBalancePay,
      businessesBalance: data.map
    };
    if (data.addressType == 6 || data.addressType == 7) {
      modifyData['residentAddress.buildId'] = data.buildId || '';
      modifyData['residentAddress.buildName'] = data.buildName || '';
      if (data.addressType == 6) {
        modifyData['residentAddress.unitId'] = data.unitId || '';
        modifyData['residentAddress.unitName'] = data.unitName || '';
      }
    }
    this.setData(modifyData);
  },
  // 修改表单数据
  modifyFormData(e) {
    this.setData({
      formList: e.detail.formList
    });
  },
  // 修改产品表单数据
  modifyFormData2(e) {
    const { goodsFormList } = this.data;
    goodsFormList[e.currentTarget.dataset.index].list = e.detail.formList[0];
    this.setData({
      goodsFormList
    });
  },
  // 获取号源
  async getFonto() {
    const { data } = await $api.AAA();
  },
  // 校验
  async checkSubmit() {
    const {
      permSubmit,
      off,
      inputPhone,
      inputPerson,
      inputHouseNumber,
      addressType,
      harvestAddressId,
      shopList,
      formList,
      goodsFormList,
      residentAddress
    } = this.data;

    const { buildId, floorId, unitId } = residentAddress;
    if (!permSubmit) return;
    if (off === 2) {
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!inputPhone) {
        Toast.fail('请输入电话');
        return;
      }
      if (!reg.test(inputPhone)) {
        Toast.fail('电话号码格式错误');
        return;
      }
      if (!inputPerson) {
        Toast.fail('请输入收货人');
        return;
      }
      if ((addressType == 6 || addressType == 7 || addressType == 8) && (!buildId || !floorId || !unitId)) {
        Toast.fail('请选择' + residentAddress.title);
        return;
      }

      if (!inputHouseNumber && (addressType == 4 || addressType == 6 || addressType == 7 || addressType == 8)) {
        Toast.fail('请输入门牌号');
        return;
      }
    }

    if (!harvestAddressId) {
      Toast.fail('请添加地址');
      return;
    }

    for (let item of shopList.list) {
      for (let item2 of item.list) {
        if (item2.goodsType === 4 && !item2.serveTime) {
          Toast.fail('请选择服务时间');
          return;
        }
      }
    }

    // let goodsFormList = this.data.goodsFormList
    if (goodsFormList && goodsFormList.length > 0) {
      for (let key in goodsFormList) {
        if (!this.selectComponent('.custom-form' + key).validate()) {
          return;
        }
      }
    }

    if (formList && formList.length > 0 && !this.selectComponent('#custom-form').validate()) {
      return;
    }

    return true;
  },
  // 提交订单
  async submitOrder() {
    if (!(await this.checkSubmit())) return;
    const { payType, totalPrice } = this.data;
    let message = null;
    if (payType === '1') message = '确定支付' + this.data.payableAmount + '元？';
    if (payType === '2') message = '确认微信支付?';
    if (payType === '3') message = '确定货到付款？';
    if (payType === '4') message = '确定他人代付？';
    if (payType === '6') message = '确定线下月结？';
    if (payType === '7') message = '确定线下余额支付？';
    await Dialog.confirm({
      title: '提示',
      message: totalPrice === 0 ? '是否0元支付' : message
    });
    let harvestAddressId = this.data.harvestAddressId;
    if (this.data.off === 2) {
      harvestAddressId = await this.saveAddress();
    }
    const shopList = JSON.parse(JSON.stringify(this.data.shopList));
    let waiterExpectedDate = '';
    shopList.list.forEach(item => {
      item.list.find(item2 => item2.goodsType === 4 && (waiterExpectedDate = item2.serveTime));
      delete item.optimizeDate;
      if (!item.selectedTime) return;
      item.expectedTimeStr = item.selectedTime;
      item.earliestTime = item.selectedTime;
      delete item.selectedTime;
    });
    let params = {
      orderAttrs: [...this.data.goodsFormList.flatMap(item => item.list), ...(this.data.formList.flat() || [])],
      beeperId: Number(this.data.beeperId),
      btnId: this.data.btnId,
      btnServerClassifyIds: this.data.btnServerClassifyIds,
      queryType: this.data.queryType,
      params: shopList.list,
      payType: Number(payType),
      amount: this.data.promoteGain && this.data.payType == 2 ? this.data.totalPrice : this.data.payableAmount,
      orderRemark: this.data.remark,
      voiceRemark: this.data.recordRemark,
      harvestAddressId,
      waiterExpectedDate: waiterExpectedDate ? waiterExpectedDate + ':00' : '',
      oldAmountoff: this.data.deductionFee.includes('1'),
      pmcAmountoff: this.data.deductionFee.includes('2')
    };
    const eventId = app.globalData['btnList.eventId'];
    if (eventId === 18) {
      // 挂号对接
      let timerinterval = app.globalData['dock.timerinterval'];
      if (timerinterval) timerinterval = timerinterval.split('-')[0];
      Object.assign(params, {
        doctorId: app.globalData['dock.doctorId'] || '',
        strDate: app.globalData['dock.date'] || '',
        timerinterval: app.globalData['dock.timerinterval'] || '',
        remark: this.data.remark,
        trantype: '区域支付' || ''
      });
    }
    // 从其它地方下单
    if (this.data.orderSource) params.orderSource = this.data.orderSource;
    if (this.data.sourceId) params.sourceId = this.data.sourceId;
    if (this.data.btnName) params.btnName = this.data.btnName;
    if (payType == 2) {
      Toast.loading({
        message: '加载中',
        forbidClick: true,
        duration: 0,
        mask: true
      });
      params.openId = wx.getStorageSync('user_open_id');
    }
    if (payType == 1) {
      Toast.loading({
        message: '支付中...',
        forbidClick: true,
        duration: 0,
        mask: true
      });
    }
    if (payType == 3 || payType == 4 || payType == 6 || payType == 7) {
      Toast.loading({
        message: '订单提交中...',
        forbidClick: true,
        duration: 0,
        mask: true
      });
    }
    $api.orderPay(params).then(res => {
      const data = res.data.data;
      if (totalPrice) {
        if (payType == 2) {
          Toast.clear();
          // 唤起微信支付
          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: () => {
              Toast.success({
                message: '支付成功',
                forbidClick: true
              });
              setTimeout(() => {
                app.globalData.beeperOrderId = this.data.beeperId;
                clearShopCartStorage();
                wx.switchTab({
                  url: '/pages/order/index'
                });
              }, 2000);
            },
            fail: err => {
              Toast.fail({
                message: '支付失败',
                forbidClick: true
              });
              setTimeout(() => {
                app.globalData.beeperOrderId = this.data.beeperId;
                clearShopCartStorage();
                wx.switchTab({
                  url: '/pages/order/index'
                });
              }, 2000);
            },
            complete: () => {}
          });
        } else {
          if (payType == 4) {
            Toast.clear();
            this.setData({
              showPayQrcode: true
            });
            clearShopCartStorage();
            return;
          }
          Toast.success({
            message: payType == 1 ? '支付成功' : '操作成功',
            forbidClick: true,
            duration: 2000,
            mask: true
          });
          setTimeout(() => {
            app.globalData.beeperOrderId = this.data.beeperId;
            clearShopCartStorage();
            wx.switchTab({
              url: '/pages/order/index'
            });
          }, 2000);
        }
      } else {
        // 0元购
        Toast.success('支付成功');
        setTimeout(() => {
          app.globalData.beeperOrderId = this.data.beeperId;
          wx.setStorageSync('shopCartData', JSON.stringify([]));
          wx.setStorageSync('formList', JSON.stringify([]));
          wx.switchTab({
            url: '/pages/order/index'
          });
        }, 2000);
      }
    });
  },

  // 关闭扫码后去订单
  closePayQrcode() {
    this.setData({
      showPayQrcode: false
    });
    setTimeout(() => {
      app.globalData.beeperOrderId = this.data.beeperId;
      wx.switchTab({
        url: '/pages/order/index'
      });
    }, 1000);
  },
  // 去备注页面
  toRemarkPage() {
    wx.navigateTo({
      url: '/subcontract/home/pages/remark/index'
    });
  },
  // 显示推广员收益
  showPromoterPopup() {
    const { showPromoter, promoteGain } = this.data;
    if (!promoteGain) return;
    this.setData({
      showPromoter: !showPromoter
    });
  },
  closePromoterPopup() {
    this.setData({
      showPromoter: false
    });
  },
  // 显示时间选择
  showTimePopup(e) {
    // expectedTimeStr是预计送达时间，deliveryTime是可选时间段,selectedTime是当前选中的时间
    let {
      item: { expectedTimeStr, deliveryTime, selectedTime },
      index
    } = e.currentTarget.dataset;
    if (!deliveryTime) return;
    this.tempIndex = index;
    expectedTimeStr = expectedTimeStr.includes('~') ? expectedTimeStr.split('~')[1] : expectedTimeStr;
    selectedTime = selectedTime || expectedTimeStr;
    const expectedTimeStrTimestamp = new Date(expectedTimeStr).getTime();
    // 可选时间段，获取15分钟的整数倍,也是明天以及后五天的可选时间
    deliveryTime = this.getFifteenTime(...deliveryTime.split('-'));
    // 今天的可选时间
    let todayTimes = [];
    expectedTimeStr = expectedTimeStr.split(' ');
    // 这里的条件是判断，如果flag为true，则是今天可到否则是明天可到
    const flag =
      Date.now() < expectedTimeStrTimestamp &&
      expectedTimeStr[0].startsWith(formatDateString(new Date(), 'yyyy-MM-dd'));
    expectedTimeStr = expectedTimeStr[1].split(':').slice(0, 2);
    // times是可选的，在预计到达时间后面可选到达时间
    const times = deliveryTime.filter(item => {
      let val = item.split(':');
      val = [Number(val[0]), Number(val[1])];
      return val[0] > expectedTimeStr[0] || (val[0] == expectedTimeStr[0] && val[1] >= expectedTimeStr[1]);
    });
    expectedTimeStr = expectedTimeStr.join(':');
    if (flag) todayTimes.push(expectedTimeStr);
    if (todayTimes.length) {
      expectedTimeStr = expectedTimeStr.split(':');
      expectedTimeStr = [Number(expectedTimeStr[0]), Number(expectedTimeStr[1])];
      todayTimes = todayTimes.concat(times);
    }
    // 获取五天时间
    let timeList = this.getDateList();
    timeList = timeList.map((item, index) => {
      let text = '';
      let children = [];
      switch (index) {
        case 0:
          text = '今天';
          children = todayTimes;
          break;
        case 1:
          text = '明天';
          children = flag ? deliveryTime : times;
          break;
        default:
          text = item.month + '月' + item.day + '号';
          children = deliveryTime;
      }
      return {
        text,
        id: item.text,
        children: children.map(item2 => ({ id: item.text + ' ' + item2, text: item2 }))
      };
    });
    // 如果今天不能送出那么就不显示今天的时间
    todayTimes.length === 0 && timeList.splice(0, 1);
    let timeActiveIndex = 0;
    let timeActiveId = '';
    timeList.find((item, index) => {
      const val = item.children.find(item2 => item2.id == selectedTime);
      if (val) {
        timeActiveIndex = index;
        timeActiveId = val.id;
        return true;
      }
    });
    this.setData({
      showTime: true,
      timeList,
      timeActiveIndex,
      timeActiveId
    });
  },
  // 获取最近五天的年月日
  getDateList() {
    let arr = [1, 2, 3, 4, 5];
    const date = new Date();
    arr = arr.map((_, index) => {
      const date2 = new Date(date.getTime() + index * 24 * 60 * 60 * 1000);
      const text = formatDateString(date2, 'yyyy-MM-dd');
      const month = date2.getMonth() + 1;
      return {
        text,
        year: date2.getFullYear(),
        month: month < 10 ? '0' + month : month,
        day: date2.getDate()
      };
    });
    return arr;
  },
  // 获取15的整数倍时间
  getFifteenTime(startTime, endTime) {
    startTime = startTime.split(':');
    startTime = [startTime[0], startTime[1]];
    endTime = endTime.split(':');
    endTime = [endTime[0], endTime[1]];
    return fifteenTimes.filter(item => {
      const val = item.split(':');
      const val1 = Number(val[0]);
      const val2 = Number(val[1]);
      const val3 = Number(startTime[0]);
      const val4 = Number(startTime[1]);
      const val5 = Number(endTime[0]);
      const val6 = Number(endTime[1]);
      const startFlag = (val1 == val3 && val4 < val2) || val1 > val3;
      const endFlag = (val1 == val5 && val6 > val2) || val5 > val1;
      return startFlag && endFlag;
    });
  },
  // 关闭时间选择
  closeTimePopup() {
    this.setData({
      showTime: false
    });
  },
  timeClickNav({ detail = {} }) {
    this.setData({
      timeActiveIndex: detail.index || 0
    });
  },
  timeClickItem({ detail = {} }) {
    const { shopCartListTwo } = this.data;
    shopCartListTwo[this.tempIndex].selectedTime = detail.id;
    shopCartListTwo[this.tempIndex].optimizeDate = getOptimizeDateTwo(detail.id);
    this.setData({
      timeActiveId: detail.id,
      shopCartListTwo,
      showTime: false
    });
  },
  async getServerTimes(date) {
    let res = await $api.getWaiterRelationListTime({ date, variantId: this.variantId });
    res = res.data.data || [];
    // (res.data.data||[]).forEach(item=>{
    //   arr = arr.filter(item2=>{
    //     console.log(compareTime(item.begin,item2.begin),compareTime(item.end,item2.end))
    //     if(compareTime(item.begin,item2.begin)<1&&compareTime(item.end,item2.end)>-1) return false
    //     return true
    //   })
    //   arr.push(item)
    // })

    this.setData({
      serveTimes: res,
      'showServeTime.empty': res.length ? false : true
    });
  },
  // 显示服务时间范围
  async showServeTimeRangePopup(e) {
    const {
      item: { serveTime, variantId },
      index,
      index2
    } = e.currentTarget.dataset;
    this.variantId = variantId;
    this.shopCartIndex = index;
    this.shopCartIndex2 = index2;
    const { showServeTime, serveDates } = this.data;
    let dateObj = {};
    if (serveTime) {
      let arr = serveTime.split(' ');
      dateObj = serveDates.find(item => item.date == arr[0]);
      dateObj && (dateObj.selected = true);
      showServeTime.time = arr[1];
    } else {
      serveDates[0].selected = true;
      dateObj = serveDates[0];
    }
    await this.getServerTimes(dateObj.date);
    // let res = await $api.getWaiterRelationListTime({date:dateObj.date,variantId})
    // res = res.data.data||[]
    this.setData({
      serveDates,
      showServeTimeRange: true
    });
  },
  // 选择服务日期
  selectServeDate(e) {
    const { index } = e.currentTarget.dataset;
    const { serveDates } = this.data;
    serveDates.forEach((item, i) => (i == index ? (item.selected = true) : (item.selected = false)));
    this.setData({
      serveDates
    });
    this.getServerTimes(serveDates[index].date);
  },
  // 选择服务时间范围
  selectServeTimeRange(e) {
    const { begin, end } = e.currentTarget.dataset.item;
    // this.startMinute = startTime
    // this.startTime = endTime
    let { showServeTime } = this.data;
    const arr = begin.split(':').map(item => Number(item));
    const arr2 = end.split(':').map(item => Number(item));
    showServeTime.minHour = arr[0];
    showServeTime.maxHour = arr2[0];
    this.startMinute = arr[1];
    this.endMinute = arr2[1];
    showServeTime.show = true;
    this.setData({
      showServeTime
    });
    this.changeServeTime();
  },
  closeServeTimeRangePopup() {
    this.setData({
      showServeTimeRange: false,
      'showServeTime.empty': false
    });
  },
  // 确定选择服务时间
  confirmServeTime(e) {
    const { serveDates } = this.data;
    const prop = `shopCartListTwo[${this.shopCartIndex}].list[${this.shopCartIndex2}].serveTime`;
    this.setData({
      [prop]: serveDates.find(item => item.selected).date + ' ' + e.detail,
      'showServeTime.show': false,
      showServeTimeRange: false
    });
  },
  // 改变服务选择
  changeServeTime() {
    const arr = this.selectComponent('#servetimeid')
      .picker.getValues()
      .map(item => Number(item));
    let hour = arr[0];
    let minute = arr[1];
    const { showServeTime } = this.data;
    const { minHour, maxHour } = showServeTime;
    if (hour == minHour && hour < maxHour) {
      console.log('A');
      showServeTime.minMinute = this.startMinute;
      minute < this.startMinute && (minute = this.startMinute);
      showServeTime.maxMinute = 59;
    } else if (hour > minHour && hour < maxHour) {
      console.log('B');
      showServeTime.minMinute = 0;
      showServeTime.maxMinute = 59;
    } else if (hour == minHour && hour == maxHour) {
      console.log('C');
      showServeTime.minMinute = this.startMinute;
      showServeTime.maxMinute = this.endMinute;
    } else if (hour > minHour && hour == maxHour) {
      console.log('D');
      showServeTime.minMinute = 0;
      showServeTime.maxMinute = this.endMinute;
      minute > this.endMinute && (minute = this.endMinute);
    } else if (hour > maxHour) {
      console.log('E');
      hour = maxHour;
      minute = this.endMinute;
      maxHour == minHour && (showServeTime.minMinute = this.startMinute);
      showServeTime.maxMinute = this.endMinute;
    } else if (hour < minHour) {
      console.log('F');
      hour = minHour;
      minute = this.startMinute;
      maxHour == minHour && (showServeTime.maxMinute = this.endMinute);
      showServeTime.minMinute = this.startMinute;
    }
    showServeTime.time = hour + ':' + minute;
    this.setData({
      showServeTime
    });
  },
  closeServeTimePopup() {
    this.setData({
      'showServeTime.show': false
    });
  },
  handleDeductionFeeChange(event) {
    let totalPrice = this.data.shopList.list.reduce((a, b) => a + b.payAmount, 0);
    let payableAmount = this.data.shopList.list.reduce((a, b) => a + b.payableAmount, 0);
    if (event.detail.includes('1')) {
      totalPrice = parseFloat((totalPrice - this.data.shopList.discountOld).toFixed(2));
      payableAmount = parseFloat((payableAmount - this.data.shopList.discountOld).toFixed(2));
    }
    if (event.detail.includes('2')) {
      totalPrice = parseFloat((totalPrice - this.data.shopList.discountPmc).toFixed(2));
      payableAmount = parseFloat((payableAmount - this.data.shopList.discountPmc).toFixed(2));
    }
    this.setData({ deductionFee: event.detail, payableAmount, totalPrice });
  }
});
